use rodio::{Decoder, OutputStream, Sink};
use std::fs::File;
use std::io::BufReader;
use std::thread::sleep;
use std::time::{Duration, Instant};
use focus90min::Config;

fn main() {
    let config = Config::default();
    run(config);
}

fn run(config: Config) {
    let range = config.short_break.random_range;
    for _i in 0..config.cycle_num {
        let unit = 60;
        let start_time = Instant::now();
        let end_time = start_time + config.focus_duration;
        // 播放开始提示
        println!("Please focus");
        play_tone(&config.long_break.tone);
        's: loop {
            // 生成一个随机数
            let random_minutes = rand::random_range(range.clone());
            println!("Wait {} minutes", random_minutes);
            sleep(Duration::from_secs((random_minutes * unit) as u64));
            // 播放开始提示
            println!("short break");
            play_tone(&config.short_break.tone);
            sleep(Duration::from_secs(10));
            println!("Short break end");
            play_tone(&config.short_break.tone);
            if Instant::now() >= end_time {
                println!("Focus end");
                play_tone(&config.long_break.tone);
                break 's;
            }
        }
        // 休息20分钟
        println!("Long break");
        sleep(config.long_break.duration);
        println!("Long break end")
    }
}

fn play_tone(tone: &String) {
    // 获取默认的音频输出设备
    let (_stream, stream_handle) = OutputStream::try_default().unwrap();

    // 加载音频文件
    let file = BufReader::new(File::open(tone).unwrap());
    let source = Decoder::new(file).unwrap();

    // 创建播放器并播放音频
    let sink = Sink::try_new(&stream_handle).unwrap();
    sink.append(source);
    sink.sleep_until_end();
}
